package com.chenyue.cm.api.upload;

import com.chenyue.cm.bean.Success;
import com.chenyue.cm.common.constant.ErrorCode;
import com.chenyue.cm.utils.MD5Util;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author libingxing
 */
@Api(tags = "/图片上传")
@RestController
@RequestMapping("/api")
public class ApiUploadController {

    @Value("${lcmaster.upload.apiUploadPath}")
    private String apiUploadPath;

    @PostMapping(value = "/uploadImg", headers = "content-type=multipart/form-data")
    @ApiOperation("图片上传")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "图片文件", name = "image", dataType = "MultipartFile", required = true),
            @ApiImplicitParam(value = "图片名称", name = "picName", dataType = "string")
    })
    public Success<Object> uploadImg(
            @RequestParam("image") MultipartFile[] files,
            @RequestParam(value = "picName", required = false) String picName
    ) {
        StringBuffer sBuffer = new StringBuffer();
        int i = 0;
        for (MultipartFile file : files) {
            if (file != null) {
                String fileType;
                String fileName = file.getOriginalFilename();
                // 判断文件类型
                assert fileName != null;
                fileType = fileName.contains(".")
                        ? fileName.substring(fileName.lastIndexOf("."))
                        : null;
                if (fileType != null) {
                    if (!checkImageFileType(fileType)) {
                        return Success.error(ErrorCode.UPLOAD_FILE_TYPE_ERROR.getMsg());
                    }

                    if (file.getSize() > 10000000) {
                        return Success.error(ErrorCode.UPLOAD_FILE_MAX_SIZE_LIMIT.getMsg());
                    }
                    if (file.getSize() == 0) {
                        return Success.error(ErrorCode.UPLOAD_FILE_EMPTY.getMsg());
                    }

                    // 图片类全部相册管理
                    String uploadPath = "";

                    if (picName == null) {
                        picName = MD5Util.getMD5(System.currentTimeMillis() + fileName, false, 16);
                    }

                    try {
                        uploadPath = saveImage(file, picName, fileType);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    // 验证文件失败提示
                    String message;
                    if (StringUtils.isEmpty(uploadPath)) {
                        message = "上传图片失败!";
                    } else {
                        message = null;
                    }
                    if (message == null) {
                        if (i > 0) {
                            sBuffer.append(",");
                        }
                        sBuffer.append(uploadPath);
                        i++;
                    } else {
                        return Success.error(message);
                    }
                } else {
                    System.out.println("文件类型为空");
                }
            } else {
                System.out.println("没有找到相对应的文件");
            }
        }
        return Success.success(sBuffer);
    }

    /**
     * 图片上传的类
     *
     * @param image       文件
     * @param orgFileName 文件名
     * @param fileType    文件类型
     */
    public String saveImage(MultipartFile image, String orgFileName, String fileType) throws IOException {
        String imageName = String.format("%s/%s" + fileType, apiUploadPath, orgFileName);

        File imageFile = new File(imageName);

        if (!imageFile.getParentFile().exists()) {
            imageFile.getParentFile().mkdirs();
        }

        image.transferTo(new File(imageFile.getAbsolutePath()));
        return "/" + imageName;
    }

    /**
     * 判断一个文件是否是图片类型
     *
     * @param type 文件类型
     * @return 是否是图片类型
     */
    public boolean checkImageFileType(String type) {
        String[] types = {".PNG", ".JPG", ".JPEG", ".BMP", ".GIF", "JIFF"};
        boolean res = false;
        for (String t : types) {
            if (t.equals(type.toUpperCase())) {
                res = true;
                break;
            }
        }
        return res;
    }

}
